<?php 
namespace XFCore\controllers\admin;
use lib\BaseController;
use lib\XFCaptcha;
use XFCore\traits\AdminTraits;
use lib\Examine;
class AjaxController extends BaseController{
    use AdminTraits;
    public function __construct(){
       parent::__construct();
       $this->Captcha = new XFCaptcha(CaptchaCode);
    }
    public function login($get,$postdata){
        if($this->islogin_admin==1)exitjson(-1,"您已登录");
        if(!$this->Captcha->XYcaptcha($postdata['code_input']))exitjson(-1,'验证码为空或错误！');
        $admin_user = $postdata['admin_user'];
        $admin_pass = $postdata['admin_pass'];
        if(empty($admin_user) || empty($admin_pass))exitjson(-1,'账号和密码不可为空');
        
        $adminrow = $this->db->adminrow($admin_user);
        if(!$adminrow){
             createLog("尝试登录后台但账号错误-提交的账户为：".$admin_user,http_ip() , 'admin');
             exitjson(-1,'账号或密码错误 请核对后在试！');
        }
        $adminnum =  $this->db->adminnum($adminrow['id'] , http_ip());
        if($adminnum >= userloginnum ){
             exitjson(-1,'您已尝试登录 ' . userloginnum. ' 次未登录成功 已被禁止登录');
        }
        
        $pwd = md5($adminrow['salt'].$admin_pass.$adminrow['salt'].md5($adminrow['salt'].$admin_pass.$adminrow['salt'].$admin_pass.$adminrow['salt']).$adminrow['salt'].$admin_pass.$adminrow['salt']);
        if($adminrow['pwd'] != $pwd){
            $this->db->adminupnum($adminrow['id'] , http_ip());
            
            createLog(' 尝试登录后台但密码错误-提交的密码为:'.$admin_pass,http_ip() , 'admin');
            
            $adminnum = number_format(userloginnum-$adminnum,0);
            
            exitjson(-1,'账号或密码错误 请核对后在试！您还可尝试登录 :'. $adminnum.'次');
        }
        $session=md5($admin_user.$pwd.$this->globalState->get('password_hash'));
        $expiretime=time()+432000;
        $token=aes256auth("{$admin_user}\t{$session}\t{$expiretime}",$this->conf['syskey'],'ENCODE');
        setcookie("admin_token", $token, $expiretime,'/');
        createLog('登录后台成功',http_ip(),'admin');
        $this->db->adminupnum($adminrow['id'] , http_ip() , '0',true);
        exitjson(1,"登录成功");
        
    }
    public function Set(){
        if($this->islogin_admin!=1)exitjson(-1,"请先登录");
         try {
            // 使用新的更新方法
            $result = $this->CACHE->updateConfig($_POST);
            
            // 记录日志
            createLog('修改设置状态', http_ip() , 'admin');
            
            if($result) {
                exitjson(1, '修改成功');
            } else {
                exitjson(-1, '修改失败');
            }
        } catch (Exception $e) {
            exitjson(-1, '修改失败：' . $e->getMessage());
        }
    }
    public function emailcs(){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $mail_name = $this->conf['mail_recv'] ? $this->conf['mail_recv'] : $this->conf['mail_name'];
        if(!empty($mail_name)){
             $result = send_mail($mail_name, '邮件发送测试。', '这是一封测试邮件！<br/><br/>来自：' . $this->httphost);
             if($result==1){
                 exitjson(200,"邮件发送成功");
             }else{
                 exitjson(-1,"邮件发送失败");
             }
        }else{
            exitjson(500,"您还未设置邮箱");
        }
    }
    public function phonecs(){
        if($this->islogin_admin!=1)exitjson(-1,"请先登录！");
        $code = rand(111111,999999);
        exit(send_sms($this->conf['sms_csphone'],$code));
    }
    public function ordergetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $params = ['ispay', 'trade_no', 'out_trade_no', 'pid'];
        $where = [];
        
        // 使用循环处理条件构建
        foreach ($params as $param) {
            if (!empty($get[$param])) {
                if ($param === 'ispay') {
                    $where['status'] = $get[$param] === 'yes' ? '1' : '0';
                } else {
                    $where[$param] = $get[$param];
                }
            }
        }
        $getCount = $this->db->select("order","count(*) as count",$where)['result'][0]['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("order","*",$where,['orderBy'=>'addtime desc','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function consumeall() {
        if($this->islogin_admin!=1) exitjson(-1,"请先登录！");
        
        $today = date("Y-m-d");
        $startTime = $today . " 00:00:00";
        $endTime = $today . " 23:59:59";
        $lastday = date("Y-m-d", strtotime("-1 day"));
        $startTimeYesterday = $lastday . " 00:00:00";
        $endTimeYesterday = $lastday . " 23:59:59";
    
        // 今日统计
        $todayStats = $this->db->complexSelect(
            "order",
            "COUNT(*) as total_orders,
             COUNT(CASE WHEN status = 1 THEN 1 END) as paid_orders,
             COALESCE(SUM(CASE WHEN status = 1 THEN money END), 0) as paid_amount,
             COALESCE(SUM(money), 0) as total_amount",
            [
                'addtime' => [
                    'operator' => 'between',
                    'start' => $startTime,
                    'end' => $endTime
                ]
            ]
        )['result'][0];
    
        // 昨日统计
        $yesterdayStats = $this->db->complexSelect(
            "order",
            "COUNT(*) as total_orders,
             COUNT(CASE WHEN status = 1 THEN 1 END) as paid_orders,
             COALESCE(SUM(CASE WHEN status = 1 THEN money END), 0) as paid_amount,
             COALESCE(SUM(money), 0) as total_amount",
            [
                'addtime' => [
                    'operator' => 'between',
                    'start' => $startTimeYesterday,
                    'end' => $endTimeYesterday
                ]
            ]
        )['result'][0];
    
        // 总支付统计
        $totalStats = $this->db->complexSelect(
            "order",
            "COALESCE(SUM(CASE WHEN status = 1 THEN money END), 0) as paid_total,
             COALESCE(SUM(money), 0) as all_total",
            []
        )['result'][0];
    
        // 计算成功率
        $todaySuccessRate = $todayStats['total_orders'] > 0 ? 
            ($todayStats['paid_orders'] / $todayStats['total_orders']) * 100 : 0;
        $yesterdaySuccessRate = $yesterdayStats['total_orders'] > 0 ?
            ($yesterdayStats['paid_orders'] / $yesterdayStats['total_orders']) * 100 : 0;
    
        // 周数据保持不变，因为已经优化过了
        $startOfWeek = date('Y-m-d', strtotime('monday this week'));
        $endOfWeek = date('Y-m-d', strtotime('sunday this week'));
        
        $weekResult = $this->db->complexSelect(
            "order",
            "DATE(addtime) as date, 
             COALESCE(SUM(CASE WHEN status = 1 THEN money END), 0) as amount",
            [
                'addtime' => [
                    'operator' => 'between',
                    'start' => $startOfWeek . ' 00:00:00',
                    'end' => $endOfWeek . ' 23:59:59'
                ]
            ],
            [
                'groupBy' => 'DATE(addtime)',
                'orderBy' => 'date ASC'
            ]
        );
    
        $dayOfWeekarr = array_fill(0, 7, 0);
        if (!empty($weekResult['result'])) {
            foreach ($weekResult['result'] as $row) {
                $dayIndex = date('N', strtotime($row['date'])) - 1;
                $dayOfWeekarr[$dayIndex] = floatval($row['amount']);
            }
        }
    
        // 支付方式统计
        $paymentTypes = ['alipay','qqpay','wxpay','usdt'];
        $paymemttypearr = [];
        
        $typeResult = $this->db->complexSelect(
            "order",
            "type, COALESCE(SUM(money), 0) as money",
            [
                'status' => '1',
                'type' => [
                    'operator' => 'in',
                    'value' => $paymentTypes
                ]
            ],
            ['groupBy' => 'type']
        );
    
        foreach ($typeResult['result'] as $row) {
            switch ($row['type']) {
                case 'wxpay':
                    $paymemttypearr['wxpay'] = $row['money'];
                    break;
                case 'alipay':
                    $paymemttypearr['alipay'] = $row['money'];
                    break;
                case 'qqpay':
                    $paymemttypearr['qqpay'] = $row['money'];
                    break;
                default:
                    $paymemttypearr['otherpay'] = $row['money'];
                    break;
            }
        }
    
        $typearr = [];
        foreach ($paymemttypearr as $type => $money) {
            $typearr[] = [
                'name' => strip_tags(pay_type($type)),
                'value' => $money
            ];
        }
    
        // 商户TOP10
        $pidResult = $this->db->complexSelect(
            "order",
            "pid, COALESCE(SUM(money), 0) AS money",
            ['status' => 1],
            [
                'groupBy' => 'pid',
                'orderBy' => 'money DESC',
                'limit' => 10
            ]
        );
    
        $moneyarr = [];
        $pidarr = [];
        foreach ($pidResult['result'] as $arr) {
            $moneyarr[] = $arr['money'];
            $pidarr[] = $arr['pid'];
        }
    
        $data = [
            'todayorder' => $todayStats['paid_orders'],
            'todaymoney' => $todayStats['paid_amount'],
            'todaysuccessRate' => number_format($todaySuccessRate,2),
            'PayAllMoney' => $totalStats['paid_total'],
            'todayPayAllMoney' => $todayStats['total_amount'],
            'todayOrderTotal' => $todayStats['total_orders'],
            'lastsuccessRate' => number_format($yesterdaySuccessRate,2),
            'AllMoney' => $totalStats['all_total'],
            'samemoney' => number_format($todayStats['paid_amount'] - $yesterdayStats['paid_amount'], 2),
            'sameRate' => number_format($todaySuccessRate - $yesterdaySuccessRate, 2),
            'sameorder' => number_format($todayStats['paid_orders'] - $yesterdayStats['paid_orders'], 0),
            'falseMoney' => number_format($totalStats['all_total'] - $totalStats['paid_total'], 2),
            'dayOfWeekarr' => $dayOfWeekarr,
            'typemoney' => $typearr,
            'pidarr' => $pidarr,
            'moneyarr' => $moneyarr,
        ];
    
        exitjson(200, 'success', array("data" => $data));
    }
    public function usergetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $type = $get['type'];
        $msg = $get['msg'];
        $where = [];
        if (!empty($type) && $msg !==false) {
            if ($type == 'pid' || $type == 'qq') {
                $where[$type] = $msg;
            }
        }
        $getCount = $this->db->select("user","count(*) as count",$where)['result'][0]['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("user","*",$where,['orderBy'=>'pid DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        
        foreach ($data as &$res) {
            $pid = $res['pid'];
            
            // 一次性获取所有支付方式的二维码状态
            $qrStatusQuery = safeSqlQuery(
                "SELECT 
                    type,
                    SUM(CASE WHEN status='1' THEN 1 ELSE 0 END) as ok_count,
                    SUM(CASE WHEN status!='1' THEN 1 ELSE 0 END) as fail_count
                FROM pay_qrlist 
                WHERE pid=:pid 
                GROUP BY type",
                ['pid' => $pid],
                'select'
            )['result'];
        
            // 转换查询结果为易用的格式
            $qrStatus = [];
            foreach ($qrStatusQuery as $status) {
                $qrStatus[$status['type']] = [
                    'ok' => $status['ok_count'] ?? 0,
                    'no' => $status['fail_count'] ?? 0
                ];
            }
        
            // 一次性获取所有时间段的订单统计
            $lastday = date("Y-m-d", strtotime("-1 day")) . ' 00:00:00';
            $today = date("Y-m-d") . ' 00:00:00';
            
            $orderStats = safeSqlQuery(
                "SELECT 
                    COALESCE(SUM(CASE WHEN addtime >= :today THEN price ELSE 0 END), 0) as today_sum,
                    COALESCE(SUM(CASE WHEN addtime >= :lastday AND addtime < :today THEN price ELSE 0 END), 0) as yesterday_sum,
                    COALESCE(SUM(price), 0) as total_sum
                FROM pay_order 
                WHERE pid=:pid AND status=1",
                [
                    'pid' => $pid,
                    'today' => $today,
                    'lastday' => $lastday
                ],
                'select'
            )['result'][0];
        
            // 构建显示信息
            $res['qxqr'] = sprintf(
                "支付宝正常：%d 失效：%d <br>QQ正常：%d 失效：%d <br>微信正常：%d 失效：%d",
                $qrStatus['alipay']['ok'] ?? 0, $qrStatus['alipay']['no'] ?? 0,
                $qrStatus['qqpay']['ok'] ?? 0, $qrStatus['qqpay']['no'] ?? 0,
                $qrStatus['wxpay']['ok'] ?? 0, $qrStatus['wxpay']['no'] ?? 0
            );
            
            $res['mghy'] = sprintf(
                "支付宝：%s <br> QQ：%s <br> 微信：%s",
                $res['alipay_free_vip_time'] > $date ? $res['alipay_free_vip_time'] : '未开通或到期了哦',
                $res['qqpay_free_vip_time'] > $date ? $res['qqpay_free_vip_time'] : '未开通或到期了哦',
                $res['wxpay_free_vip_time'] > $date ? $res['wxpay_free_vip_time'] : '未开通或到期了哦'
            );
            
            $res['sktj'] = sprintf(
                "今日收款：%s元 <br> 昨日收款：%s元 <br> 总收款：%s元",
                $orderStats['today_sum'],
                $orderStats['yesterday_sum'],
                $orderStats['total_sum']
            );
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function qrlistgetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $type = $get['type'];
        $msg = $get['msg'];
        $where = [];
        if (!empty($type) && $msg !==false) {
            if ($type == 'pid' || $type == 'type' || $type == 'beizhu'){
                $where[$type] = $msg;
            }
        }
        $getCount = $this->db->select("qrlist","count(*) as count",$where)['result'][0]['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("qrlist","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        foreach ($data as &$res){
            $res['times']  = '状态：'.cookie_zt($res['status'], $res['type'], $res['addtime'], $res['endtime'], $res['wx_name'], $res['hook_type'], $res['crontime'], $res['cookie'], $res['xf_stat'],$res['xf_type']);
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function Wechat_TrumpetgetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $getCount = $this->db->select("wechat_trumpet","count(*) as count",[])['result'][0]['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("wechat_trumpet","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        foreach ($data as &$res){
            $res['active'] = wachat_login_zt($res['login_time']);
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function RiskgetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $type = $get['type'];
        $msg = $get['msg'];
        $where = [];
        if (!empty($type) && $msg !==false) {
            if ($type == 'pid' || $type == 'url' || $type == 'content'){
                $where[$type] = $msg;
            }
        }
        $getCount = $this->db->select("risk","count(*) as count",$where)['result'][0]['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("risk","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function del_allrisk(){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        if(empty($this->db->select("risk","*",[],['limit'=>1])['count']))exitjson(-1,'无数据');
        if($this->db->delete("risk",null)){
            createLog("删除全部风控记录成功",http_ip(),'admin');
            exitjson(200,'删除成功！');
        }
        exitjson(-1,'删除失败！');
    }
    public function LoggetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $type = $get['type'];
        $msg = $get['msg'];
        $where = [];
        if (!empty($type) && $msg !==false) {
            if ($type == 'name' || $type == 'ip'){
                $where[$type] = $msg;
            }
        }
        $getCount = $this->db->select("log","count(*) as count",$where)['result'][0]['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("log","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function Del_log(){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $id = input("post")['id'];
        if(empty($id))exitjson(-1,'非法操作');
        if(empty($this->db->select("log","id",['id'=>$id],['limit'=>1])['count']))exitjson(-1,'日志记录不存在');
        if($this->db->delete("log",['id'=>$id])){
            exitjson(200,'删除成功！');
        }
        exitjson(-1,'删除失败！');
    }
    public function Del_qblog(){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        if(empty($this->db->select("log","*",[],['limit'=>1])['count']))exitjson(-1,'无数据');
        if($this->db->delete("log",null)){
            createLog("删除全部操作日志成功",http_ip(),'admin');
            exitjson(200,'删除成功！');
        }
        exitjson(-1,'删除失败！');
    }
    public function chackip(){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $ip = input("post")['ip'];
        if(empty($ip))exitjson(-1,'未知错误!');
        $res = $this->CurlUrl->ipcity($ip);
        exitjson(200,'success',$res);
    }
    public function PackagegetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $getCount = $this->db->select("package","count(*) as count",[],['single_row'=>true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("package","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function NoticegetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $getCount = $this->db->select("notice","count(*) as count",[],['single_row'=>true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("notice","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    
    public function downgetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $getCount = $this->db->select("down","count(*) as count",[],['single_row'=>true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("down","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function WorkgetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $getCount = $this->db->select("work","count(*) as count",[],['single_row'=>true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("work","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function qunemailgetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $getCount = $this->db->select("email","count(*) as count",[],['single_row'=>true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("email","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        foreach($data as &$res) {
            $res['pid'] = (!empty($res['pid'])) ? $res['pid']  : "非本站用户";
            $res['mailname'] = (!empty($res['mailname'])) ? $res['mailname'] : "未知";
           $res['type'] = ($res['type'] ==  1) ? "<font color=green>发信成功</font>" : "<font color=red>发信失败</font>";
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    public function wxyunurlgetDataList($get){
        if($this->islogin_admin!=1)exitjson(-1,'请先登录');
        $getCount = $this->db->select("wxyunurl","count(*) as count",[],['single_row'=>true])['result']['count'];
        $pagesize = $get['limit'];
        $pages = ceil($getCount / $pagesize);
        $page = isset($get['page']) ? intval($get['page']) : 1;
        $offset = $pagesize * ($page - 1);
        $result = $this->db->select("wxyunurl","*",$where,['orderBy'=>'id DESC','limit'=>"{$offset} , {$pagesize}"]);
        $data = $result['result'];
        foreach ($data as &$res){
            $res['code'] = wxyuntypetemp($res['code']);
        }
        exitjson(0,'ok',array('count'=>$getCount,'data'=>$data));
    }
    
    
}

?>